import axios from 'axios';
import { makeObservable, observable, action, flow, computed, autorun } from 'mobx';
import Todo from './Todo';

class Todos {
  constructor () {
    this.filter = 'All';
    this.todos = [];
    
    makeObservable(this, {
      filter: observable,
      todos: observable,
      add: action.bound,
      load: flow.bound,
      remove: action.bound,
      uncompletedCount: computed,
      changeFilter: action.bound,
      filterTodos: computed,
      clearCompleted: action.bound,
    });

    // 监测数据变化
    autorun(() => {
      console.log('todos has changed', this.todos);
    });
  }

  *load () {
    const { data } = yield axios.get('http://localhost:3001/todos');
    data.forEach(item => this.todos.push(new Todo(item)));
  }

  add (title) {
    this.todos.push(new Todo({ title, id: Math.random() }));
  }

  remove (id) {
    this.todos = this.todos.filter(todo => todo.id !== id);
  }

  get uncompletedCount () {
    return this.todos.reduce((t, a) => !a.isCompleted ? ++t : t, 0);
  }

  changeFilter (filter) {
    this.filter = filter;
  }

  get filterTodos () {
    switch (this.filter) {
      case 'Active':
        return this.todos.filter(todo => !todo.isCompleted);
      case 'Completed':
        return this.todos.filter(todo => todo.isCompleted);
      default:
        return this.todos;
    }
  }

  clearCompleted () {
    this.todos = this.todos.filter(todo => !todo.isCompleted);
  }
}

export default Todos;